const express = require("express");
const Router = express.Router();
const query = require("./db");
const path = require("path");
const multer = require("multer");
const { randomNum, messageAlivePushing } = require("../utils/tool");
const axios = require("axios");
const globalVars = require("../global/index");

// 设置上传文件的配置
let storage = multer.diskStorage({
  // 上传文件保存目录，无则自动创建
  // 要放到后端的static文件夹中
  destination: path.join(__dirname, "../static/images/article"),
  // 格式化文件名与后缀名
  filename: (req, file, cb) => {
    // req请求对象
    // file 文件
    // cb 回调函数，用于确认文件名
    // file.originalname 上传的原文件的名称加上后缀的
    // file.fieldname formdata数据中存放文件的属性 avatar
    let ext = path.extname(file.originalname);
    cb(null, file.fieldname + "-" + Date.now() + ext);
  },
});
// 使用配置
let upload = multer({ storage });

let imgInsertId = "";

module.exports = Router;

/**
 * 根据分类获取笔记
 */
Router.get("/getArticle", async (req, res) => {
  try {
    let { type_id, limit, page } = req.query;
    let sql = "";
    if (type_id == 0) {
      sql = `select * from article join user on article.article_author_id=user.user_id where article_status='1' order by article_time desc limit ${
        (page - 1) * limit
      },${limit}`;
    } else {
      sql = `select * from article join user on article.article_author_id=user.user_id where article_type='${type_id}' and article_status='1' order by article_time desc limit ${
        (page - 1) * limit
      },${limit}`;
    }
    let data = await query(sql);
    if (data.length === 0) {
      res.send({
        code: 400,
        msg: "获取笔记失败",
      });
      return;
    }
    res.send({
      code: 200,
      msg: "获取笔记成功",
      data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

// /**
//  * 发布笔记
//  */
// Router.post('/uploadArticle', async (req, res) => {
//     try {
//         let { article_title, article_introduction, article_coverimg, article_type, article_content } = req.body
//         let { user_id } = req.userInfo
//     } catch (error) {
//         res.send({
//             code: 0,
//             error
//         })
//     }
// })

/**
 * 请求笔记详情页数据
 */
Router.get("/getDetail", async (req, res) => {
  try {
    let { article_id, user_id } = req.query;
    let data = await query(
      `select * from article join user on article.article_author_id=user.user_id where article_id=${article_id}`
    );
    let count = await query(
      `select * from article join user on article.article_author_id=user.user_id where user_id=${user_id}`
    );
    let likeResult = await query(
      `select * from article where article_author_id=${user_id}`
    );
    let typeName = await query(
      `select * from type where type_id=${data[0].article_type}`
    );

    let likeCount = 0;
    if (data.length === 0) {
      res.send({
        code: 400,
        msg: "请求笔记详情失败",
      });
      return;
    }
    likeResult.forEach((item) => {
      likeCount += Number(item.article_like);
    });
    data.forEach((item) => {
      item.count = count.length;
      item.likeCount = likeCount;
      item.typeName = typeName[0].type_name;
    });
    res.send({
      code: 200,
      msg: "请求笔记详情成功",
      data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 请求笔记所有分类
 */
Router.get("/getArticleType", async (req, res) => {
  try {
    let data = await query(`select * from type`);
    if (data.length === 0) {
      res.send({
        code: 400,
        msg: "获取笔记分类失败",
      });
      return;
    }
    res.send({
      code: 200,
      msg: "获取笔记分类成功",
      data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 上传图片到预览表，并返回这个图片
 */
Router.post("/uploadImg", upload.single("file"), async (req, res) => {
  try {
    let file = req.file;
    let imgurl = `${process.env.BASE_URL}/images/article/` + file.filename;
    let data = await query(
      `insert into preview values(${null},'${imgurl}','${new Date().getTime()}')`
    );
    imgInsertId = data.insertId;
    res.send({
      code: 200,
      msg: "上传预览图片成功",
      file,
      data,
      imgurl,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 获取已经保存的草稿
 */
Router.get("/getSaveArticle", async (req, res) => {
  try {
    let { user_id } = req.query;
    let data = await query(
      `select * from article where article_author_id='${user_id}' and article_status='3'`
    );
    if (data.length === 0) {
      res.send({
        code: 400,
        msg: "没有已保存的笔记",
      });
      return;
    }
    res.send({
      code: 200,
      msg: "成功获取已保存的笔记",
      data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 保存/发布笔记 - 使用参数化查询
 */
Router.post("/uploadArticle", upload.single("file"), async (req, res) => {
  try {
    let { article, user, type, insertId } = req.body;
    let data = {};

    // 使用参数化查询检查已保存的笔记
    let haveSaveArticle = await query(
      "SELECT * FROM article WHERE article_author_id = ? AND article_status = ?",
      [user.user_id, "3"]
    );

    // 获取preview表的图片路径
    let imgPath = article.imgUrl;
    // if (insertId) {
    //   let insertIdList = insertId.split(",");
    //   for (const item of insertIdList) {
    //     // 参数化查询获取预览数据
    //     let previewData = await query(
    //       "SELECT * FROM preview WHERE img_id = ?",
    //       [parseInt(item)]
    //     );
    //     if (previewData.length > 0) {
    //       imgPath += previewData[0].img_path + ",";
    //     }
    //   }
    //   if (imgPath.endsWith(",")) {
    //     imgPath = imgPath.slice(0, -1);
    //   }
    // } else {
    //   imgPath += article.imgUrl || "";
    // }

    if (haveSaveArticle.length) {
      // 已有保存的笔记
      data = await query(
        `
                UPDATE article SET
                article_title = ?,
                article_introduction = ?,
                article_content = ?,
                article_coverimg = ?,
                article_author_id = ?,
                article_type = ?,
                article_status = ?,
                article_like = ?,
                article_time = ?,
                article_collect = ?
                WHERE article_id = ?
            `,
        [
          article.title,
          article.intro,
          article.valueHtml,
          imgPath,
          user.user_id,
          article.typeSelected,
          type === "publish" ? "1" : "3",
          "0",
          new Date().getTime().toString(),
          "0",
          haveSaveArticle[0].article_id,
        ]
      );
    } else {
      // 没有已经保存的笔记
      data = await query(
        `
                INSERT INTO article (
                    article_title, article_introduction, article_content, 
                    article_coverimg, article_author_id, article_type, 
                    article_status, article_like, article_time, article_collect
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            `,
        [
          article.title,
          article.intro,
          article.valueHtml,
          imgPath,
          user.user_id,
          article.typeSelected,
          type === "publish" ? "1" : "3",
          "0",
          new Date().getTime().toString(),
          "0",
        ]
      );
    }

    res.send({
      code: 200,
      msg: "笔记上传成功",
      data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error: error.message,
    });
  }
});

/**递归处理评论数据
 */
async function resultAction(arr) {
  for (const item of arr) {
    let childrenArr = await query(
      `select * from review join user on review.user_id=user.user_id where article_id=${item.article_id} and review_extend=${item.review_id}`
    );
    item.childrenList = childrenArr;
    if (childrenArr.length) {
      for (const i of childrenArr) {
        i.childrenList = resultAction(childrenArr);
      }
    }
  }
  return arr;
}

/**
 * 请求评论数据
 */
// Router.get('/getReviewList', async (req, res) => {
//     try {
//         let { article_id } = req.query
//         // data：所有评论不分层返回
//         let data = await query(`select * from review join user on review.user_id=user.user_id where article_id=${article_id}`)
//         // result：第一层评论
//         // let result = data.filter(item => item.review_extend === 0)
//         // 在第一层评论中加入childrenList数组属性，里面存放该评论的回复（第二层评论）
//         // for (const item of result) {
//         //     let childrenItem = await query(`select * from review where article_id=${article_id} and review_extend=${item.review_id}`)
//         //     item.childrenList = childrenItem
//         // }
//         // let endResult = await resultAction(result)
//         if (data.length === 0) {
//             res.send({
//                 code: 400,
//                 msg: '当前笔记没有评论',
//             })
//             return
//         }
//         res.send({
//             code: 200,
//             msg: '请求评论成功',
//             // result: data
//             endResult:data
//         })
//     } catch (error) {
//         console.log(error);
//         res.send({
//             code: 0,
//             error
//         })
//     }
// })

// 递归获取根评论的ID
async function findRootReviewId(review) {
  if (!review || review.review_extend === 0) {
    return review.review_id;
  }
  let rootReviewId = review.review_extend;
  let rootReviews = await query(
    `select * from review where review_id=${rootReviewId}`
  );
  if (!rootReviews || rootReviews.length === 0) {
    return review.review_id;
  }
  let rootReview = rootReviews[0];
  return await findRootReviewId(rootReview);
}

Router.get("/getReviewList", async (req, res) => {
  try {
    let { article_id } = req.query;
    // data：所有评论不分层返回
    let data = await query(
      `select * from review join user on review.user_id=user.user_id where article_id=${article_id}`
    );
    for (const item of data) {
      delete item.user_password;
      if (item.review_extend) {
        let extend = data.find((i) => i.review_id === item.review_extend);
        let root_review_id = await findRootReviewId(item);
        item.extend = {
          user_name: extend.user_name,
          review_content: extend.review_content,
          root_review_id: root_review_id,
        };
      }
    }

    if (data.length === 0) {
      res.send({
        code: 400,
        msg: "当前笔记没有评论",
      });
      return;
    }
    res.send({
      code: 200,
      msg: "请求评论成功",
      // result: data
      endResult: data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 发表评论
 */
Router.post("/postReview", async (req, res) => {
  try {
    let { review, user, article_id, article_author_id } = req.body;
    let data = await query(
      `insert into review values(${null},${
        user.user_id
      },${article_id},'${review}','${new Date().getTime()}',0)`
    );
    // 信息表增加的推送信息数据
    let messageResult = await query(
      `insert into message values(${null},'评论了您的笔记','${review}','pinglun','${Date.now()}',${article_author_id},${
        user.user_id
      },${article_id},'0')`
    );
    let messagePushingData = await query(
      `select * from message inner join article on message.message_to_user_id=article.article_author_id inner join user on message.message_from_user_id=user.user_id where message_to_user_id=${article_author_id} and message_from_user_id<>message_to_user_id group by message_id`
    );
    // 推送
    messageAlivePushing(String(article_author_id), messagePushingData);
    res.send({
      code: 200,
      msg: "评论成功",
      data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 回复评论
 */
Router.post("/recoverReview", async (req, res) => {
  try {
    let { review_content, review_extend, user, article_id, sender_id } =
      req.body;
    let data = await query(
      `insert into review value(${null},${
        user.user_id
      },${article_id},'${review_content}','${new Date().getTime()}',${review_extend})`
    );
    // 信息表增加的推送信息数据
    let messageResult = await query(
      `insert into message values(${null},'回复了您的评论','${review_content}','huifu','${Date.now()}',${sender_id},${
        user.user_id
      },${article_id},'0')`
    );
    let messagePushingData = await query(
      `select * from message inner join article on message.message_to_user_id=article.article_author_id inner join user on message.message_from_user_id=user.user_id where message_to_user_id=${sender_id} and message_from_user_id<>message_to_user_id group by message_id`
    );
    // 推送
    messageAlivePushing(String(sender_id), messagePushingData);
    res.send({
      code: 200,
      msg: "回复评论成功",
      data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 判断当前笔记是否已经被当前用户收藏
 */
Router.get("/checkCollect", async (req, res) => {
  try {
    let { user_id, article_id } = req.query;
    let data = await query(
      `select * from collect where article_id=${article_id} and user_id=${user_id}`
    );
    if (data.length === 0) {
      res.send({
        code: 200,
        msg: "当前笔记还没有被当前用户收藏",
        sta: false,
      });
      return;
    }
    res.send({
      code: 200,
      msg: "当前笔记已经被当前用户收藏",
      sta: true,
      data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 点击收藏按钮,写入收藏数据，同时让笔记的收藏数+1
 */
Router.post("/collect", async (req, res) => {
  try {
    let { user_id, article_id, collect_num, collect_status } = req.body;
    let data = ""; // 增加/删除的收藏表数据
    let result = ""; // 笔记表收藏数更新的数据
    let messageResult = ""; // 信息表增加的推送信息数据
    let messageSSEData = {}; // 主动构造的通过SSE返回到客户端的数据
    let articleData = await query(
      `select * from article where article_id=${article_id}`
    ); // 要收藏的笔记信息
    let { article_author_id } = articleData[0];
    // 当前是否已经收藏
    if (collect_status) {
      // 删除收藏数据
      data = await query(
        `delete from collect where user_id=${user_id} and article_id=${article_id}`
      );
      // 笔记收藏数-1
      result = await query(
        `update article set article_collect='${
          Number(collect_num) - 1
        }' where article_id=${article_id}`
      );
      // 生成推送信息
      messageResult = await query(
        `insert into message values(${null},'取消收藏了您的笔记','','shoucang','${Date.now()}',${article_author_id},${user_id},${article_id},'0')`
      );
    } else {
      data = await query(
        `insert into collect values(${null},${user_id},${article_id})`
      );
      result = await query(
        `update article set article_collect='${
          Number(collect_num) + 1
        }' where article_id=${article_id}`
      );
      messageResult = await query(
        `insert into message values(${null},'收藏了您的笔记','','shoucang','${Date.now()}',${article_author_id},${user_id},${article_id},'0')`
      );
    }
    // let messageData = await query(`select * from message where message_id=${messageResult.insertId}`)
    // messageSSEData = { ...messageData[0] }
    // console.log(messageSSEData);

    let messagePushingData = await query(
      `select distinct * from message left join article on message.message_article_id=article.article_id join user on message.message_from_user_id=user.user_id where message_to_user_id=${article_author_id} and message_from_user_id<>message_to_user_id order by message_time desc`
    );
    // 推送消息
    messageAlivePushing(String(article_author_id), messagePushingData);

    res.send({
      code: 200,
      msg: "收藏/取消成功",
      data,
      result,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 判断当前笔记是否已经被当前用户点赞
 */
Router.get("/checkLike", async (req, res) => {
  try {
    let { user_id, article_id } = req.query;
    let data = await query(
      `select * from likes where article_id=${article_id} and user_id=${user_id}`
    );
    if (data.length === 0) {
      res.send({
        code: 200,
        msg: "当前笔记还没有被当前用户点赞",
        sta: false,
      });
      return;
    }
    res.send({
      code: 200,
      msg: "当前笔记已经被当前用户点赞",
      sta: true,
      data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 点击点赞按钮,写入点赞数据，同时让笔记的点赞数+1
 */
Router.post("/like", async (req, res) => {
  try {
    let { user_id, article_id, like_num, like_status } = req.body;
    let data = ""; // 增加/删除的点赞表数据
    let result = ""; // 笔记表点赞数更新的数据
    let messageResult = ""; // 信息表增加的推送信息数据
    let articleData = await query(
      `select * from article where article_id=${article_id}`
    );
    let { article_author_id } = articleData[0];
    // 当前是否已经点赞
    if (like_status) {
      // 删除点赞数据
      data = await query(
        `delete from likes where user_id=${user_id} and article_id=${article_id}`
      );
      // 笔记点赞数-1
      result = await query(
        `update article set article_like='${
          Number(like_num) - 1
        }' where article_id=${article_id}`
      );
      // 生成推送信息
      messageResult = await query(
        `insert into message values(${null},'取消点赞了您的笔记','','dianzan','${Date.now()}',${article_author_id},${user_id},${article_id},'0')`
      );
    } else {
      data = await query(
        `insert into likes values(${null},${user_id},${article_id})`
      );
      result = await query(
        `update article set article_like='${
          Number(like_num) + 1
        }' where article_id=${article_id}`
      );
      messageResult = await query(
        `insert into message values(${null},'点赞了您的笔记','','dianzan','${Date.now()}',${article_author_id},${user_id},${article_id},'0')`
      );
    }

    let messagePushingData = await query(
      `select distinct * from message inner join article on message.message_article_id=article.article_id join user on message.message_from_user_id=user.user_id where message_to_user_id=${article_author_id} and message_from_user_id<>message_to_user_id order by message_time desc`
    );
    // 推送消息
    messageAlivePushing(String(article_author_id), messagePushingData);

    res.send({
      code: 200,
      msg: "点赞/取消成功",
      data,
      result,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 请求笔记作者的最近笔记
 */
Router.get("/lastArticleList", async (req, res) => {
  try {
    let { article_author_id } = req.query;
    let data = await query(
      `select * from article where article_author_id=${article_author_id} order by article_id desc limit 5`
    );
    if (data.length === 0) {
      res.send({
        code: 400,
        msg: "该用户没有其他笔记",
      });
      return;
    }
    res.send({
      code: 200,
      msg: "请求最近笔记成功",
      data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 搜索笔记
 */
Router.get("/search", async (req, res) => {
  try {
    let { text } = req.query;
    let data = await query(
      `select * from article where article_title like '%${text}%'`
    );
    if (data.length === 0) {
      res.send({
        code: 400,
        msg: "没有找到相关笔记",
      });
      return;
    }
    res.send({
      code: 200,
      msg: "搜索笔记成功",
      data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});

/**
 * 获取最近更新的作者以及笔记数据
 * 随机2个作者
 */
Router.get("/getNearList", async (req, res) => {
  try {
    // 先查用户表，获得两个随机id
    let userList = await query(`select * from user`);
    let user_id1 = randomNum(
      userList[0].user_id,
      userList[userList.length - 1].user_id
    );
    let user_id2 = randomNum(
      userList[0].user_id,
      userList[userList.length - 1].user_id
    );
    let userResult = await query(
      `select * from user where user_id=${user_id1} or user_id=${user_id2}`
    );
    let articleResult1 = await query(
      `select * from article where article_author_id=${user_id1}`
    );
    let articleResult2 = await query(
      `select * from article where article_author_id=${user_id2}`
    );
    userResult[0].articleResult =
      articleResult1.length === 0 ? [] : articleResult1;
    userResult[1].articleResult =
      articleResult2.length === 0 ? [] : articleResult2;
    res.send({
      code: 200,
      msg: "获取最近更新的作者以及笔记数据成功",
      userResult,
    });
  } catch (error) {
    console.log(error);
    res.send({
      code: 0,
      error,
    });
  }
});
